from tempfile import mktemp
from activist.Config import Config
import os
from StringIO import StringIO
import time
import twisted.cred.error


def sendMessageToAllAdministrators(message):
    from activist.DataStore import DataStore
    from activist.Text import Text
    from activist.MetaData import MetaDataFactory,MetaData

    ##message = 'SYSTEM MESSAGE: ' + message
    
    data = Text()
    data.create(message)

    if Config.debug: print "MESSAGE:",message
    for admin in DataStore.getAllAdministrators():
        admin.send_message(data)
        print "  ",admin
    

def activistLogObserver(args):
    if args['isError']:
        if args.has_key('failure') and isinstance(args['failure'],twisted.cred.error.UnauthorizedLogin):
            return
        
        try:
            body = StringIO()
            message = args['message']
            if len(message):
                message = reduce(lambda x,y: str(x) + str(y), message)
            else:
                message = "[No message]"
            body.write('Greetings,\n\nThis is the activist.ca Web application server.\nOn %s, I detected the following error:\n\nmessage: "%s".\n\n' % (time.asctime(),message))

            if args.has_key('failure'):
                body.write("There is a failure object; its details:\n\n")
                failure = args['failure']
                failure.printDetailedTraceback(file=body)

            from twisted.mail.smtp import sendmail
            emails = Config.email_errors_to
            defered = sendmail(Config.email_host, "errors@activist.ca", emails, body.getvalue())
            
            addeys = ", ".join(map(lambda x: " at ".join(x.split('@')), Config.email_errors_to))
            sendMessageToAllAdministrators("I detected an error and sent email with details to: %s" % addeys)
        except:
            print "TERRIBLE NEWS: I was trying to send an error email, but threw an exception!"



def writeOnceAttributes(self,name,value):
    if hasattr(self, name) and name != '_hash':
        raise AttributeError, "immutable object"
    object.__setattr__(self, name, value)
    

def pdfFromEvents(writable,events):
    name = mktemp()
    temp = open( name+'.tex', 'w' )
    
    temp.write(r'''
\documentclass[landscape,letterpaper,twocolumn]{report} 
\usepackage{graphicx,pstcol,epsfig} 

\setlength{\parindent}{0pt} 
\setlength{\columnseprule}{1pt} 
\setlength{\columnsep}{0.5in} % default=10pt 
\setlength{\oddsidemargin}{-0.5in} % default=0in 
\setlength{\evensidemargin}{0in} %default=1in 
\setlength{\textwidth}{10.5in} % default=9in 
\setlength{\textheight}{7.0in} % default=5.15in
\setlength{\headheight}{0in}
\setlength{\topmargin}{0in}
\setlength{\headsep}{0in}
\pagestyle{myheadings} 

\begin{document} 

\DeclareFixedFont{\cursive}{T1}{ppl}{m}{sc}{29.9pt} 
\DeclareFixedFont{\tinycursive}{T1}{ppl}{m}{sc}{20.0pt} 
\DeclareFixedFont{\tinyfixed}{T1}{pcr}{m}{sc}{10.0pt} 
\DeclareFixedFont{\eventtitle}{OT1}{phv}{b}{b}{10pt} 
\DeclareFixedFont{\eventdate}{T1}{phv}{it}{it}{10pt} 
\DeclareFixedFont{\eventbody}{T1}{ptm}{n}{n}{8pt} 

\newcommand{\ActivistNetwork}{\cursive Activist Network} 

\newcommand{\Title}{ 
\begin{pspicture}(0,0)(10,4.0) 
\psset{linestyle=solid} 
\put(5,0.8){\ActivistNetwork} 
\put(5,0){\tinycursive event listings: June, 2004} 
\put(5,-0.5){\tinyfixed http://www.activist.ca} 
%%% FIXME \scalebox{0.5}{\put(4,-1.5){\epsfig{file=static/ActivistNetworkLogo.eps}}} 
\end{pspicture} 
} 

\newcommand{\Event}[3] 
{ 
\parbox{\linewidth} 
{ 
\eventtitle #1 \\ 
\eventdate #2 \vspace{0.25em} 

\eventbody #3 
\\ 
\rule{2cm}{0.5pt} 
\vspace{1pt} 
} 
} 

\thispagestyle{empty} % no page numbering 
\rput{0}(2,3){\Title} 

''')

    for listing in events:
        temp.write( "\Event{%(title)s}{%(date)s}{%(description)s\\\\%(location)s}\n\n" %
                       { 'title': listing.info().title(),
                         'date': listing.info().when(),
                         'description': listing.info().description()[:30], ## FIXME; format
                         'location': listing.info().where()._name }
                       )

    temp.write(r'''
\end{document}
''')
    temp.close()
    
    os.system( 'cd /tmp && latex %s.tex' % name )
    os.system( 'cd /tmp && dvipdf %s.dvi' % name )
    try:
        file = open( '%s.pdf'%name, 'r' )
        writable.write(file.read())
        file.close()
    except:
        pass
    os.system( 'rm %s*' % name )
    

    

